package com.seedog.mq.cli;

import com.seedog.mq.core.MessageQueue;
import com.seedog.mq.exception.TopicNotFoundException;
import com.seedog.mq.model.Message;
import com.seedog.mq.server.MessageQueueServer;
import com.seedog.mq.server.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Set;

/**
 * 消息队列管理工具，提供命令行接口来查看服务器状态、管理主题等操作
 */
public class MessageQueueAdminTool {
    private static final Logger logger = LoggerFactory.getLogger(MessageQueueAdminTool.class);
    private static MessageQueueServer server;

    /**
     * 主方法，提供命令行接口
     */
    public static void main(String[] args) {
        try {
            if (args == null || args.length == 0) {
                printHelp();
                return;
            }

            String command = args[0].toLowerCase();
            switch (command) {
                case "start":
                    startServer(args);
                    break;
                case "status":
                    checkStatus();
                    break;
                case "topics":
                    listTopics();
                    break;
                case "create-topic":
                    if (args.length > 1) {
                        createTopic(args[1]);
                    } else {
                        System.out.println("错误：请指定主题名称");
                    }
                    break;
                case "delete-topic":
                    if (args.length > 1) {
                        deleteTopic(args[1]);
                    } else {
                        System.out.println("错误：请指定主题名称");
                    }
                    break;
                case "help":
                case "-h":
                case "--help":
                    printHelp();
                    break;
                default:
                    System.out.println("未知命令：" + command);
                    printHelp();
                    break;
            }
        } catch (Exception e) {
            logger.error("命令执行出错", e);
            System.out.println("命令执行出错: " + e.getMessage());
        }
    }

    /**
     * 启动服务器
     */
    private static void startServer(String[] args) {
        try {
            ServerConfig config = ServerConfig.getDefault();
            // 解析命令行参数
            for (int i = 1; i < args.length; i++) {
                if (args[i].equals("--port") || args[i].equals("-p") && i + 1 < args.length) {
                    config.setNodePort(Integer.parseInt(args[i + 1]));
                    i++;
                } else if (args[i].equals("--distributed") || args[i].equals("-d")) {
                    config.setDistributedMode(true);
                }
            }

            server = new MessageQueueServer(config);
            server.start();
            System.out.println("SeeDog消息队列服务器已启动");
            System.out.println("配置: " + config);
            System.out.println("服务器正在运行，按Ctrl+C停止...");
            
            // 保持主线程运行，直到收到关闭信号
            CountDownLatch latch = new CountDownLatch(1);
            latch.await();
        } catch (InterruptedException e) {
            // 捕获中断异常，优雅地关闭服务器
            Thread.currentThread().interrupt();
            logger.info("接收到中断信号，正在关闭服务器...");
            if (server != null) {
                server.shutdown();
            }
        } catch (Exception e) {
            System.out.println("服务器启动失败: " + e.getMessage());
            logger.error("服务器启动失败", e);
        }
    }

    /**
     * 检查服务器状态
     */
    private static void checkStatus() {
        // 默认端口和主机
        int port = 7777;
        String host = "localhost";
        
        try {
            // 尝试连接服务器进行状态检查
            Socket socket = new Socket(host, port);
            try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ) {
                // 发送状态查询命令
                out.println("STATUS");
                
                // 读取服务器响应
                String response = in.readLine();
                if (response != null && response.startsWith("RUNNING: true")) {
                    System.out.println("服务器状态: 运行中");
                    System.out.println("服务器信息: " + response);
                } else {
                    System.out.println("服务器状态: 未运行");
                    System.out.println("响应: " + (response != null ? response : "无响应"));
                }
            }
        } catch (Exception e) {
            // 如果连接失败，检查本地实例
            if (server != null && server.isRunning()) {
                System.out.println("服务器状态: 运行中 (本地实例)");
                
                // 打印服务器配置信息
                ServerConfig config = server.getConfig();
                System.out.println("服务器配置: " + config);
            } else {
                System.out.println("服务器未启动或无法连接: " + e.getMessage());
            }
        }
    }

    /**
     * 列出所有主题
     */
    private static void listTopics() {
        // 默认端口和主机
        int port = 7777;
        String host = "localhost";
        
        try {
            // 尝试连接服务器获取主题列表
            Socket socket = new Socket(host, port);
            try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ) {
                // 发送查询主题命令
                out.println("TOPICS");
                
                // 读取服务器响应
                String response = in.readLine();
                if (response != null && !response.equals("UNKNOWN_COMMAND")) {
                    if (response.isEmpty() || response.equals("No topics available")) {
                        System.out.println("当前没有创建任何主题");
                    } else {
                        String[] topics = response.split(",");
                        System.out.println("已创建的主题列表 (共" + topics.length + "个):");
                        for (String topic : topics) {
                            System.out.println("  - " + topic);
                        }
                    }
                } else {
                    System.out.println("获取主题列表失败: " + (response != null ? response : "无响应"));
                }
            }
        } catch (Exception e) {
            // 如果连接失败，检查本地实例
            if (server != null && server.isRunning()) {
                MessageQueue messageQueue = server.getMessageQueue();
                if (messageQueue == null) {
                    System.out.println("无法获取消息队列实例");
                    return;
                }

                Set<String> topics = messageQueue.getAllTopics();
                if (topics.isEmpty()) {
                    System.out.println("当前没有创建任何主题");
                } else {
                    System.out.println("已创建的主题列表 (共" + topics.size() + "个):");
                    for (String topic : topics) {
                        System.out.println("  - " + topic);
                    }
                }
            } else {
                System.out.println("服务器未启动或无法连接: " + e.getMessage());
            }
        }
    }

    /**
     * 创建主题
     */
    private static void createTopic(String topicName) {
        // 默认端口和主机
        int port = 7777;
        String host = "localhost";
        
        try {
            // 尝试连接服务器创建主题
            Socket socket = new Socket(host, port);
            try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ) {
                // 发送创建主题命令
                out.println("CREATE_TOPIC " + topicName);
                
                // 读取服务器响应
                String response = in.readLine();
                if (response != null && response.equals("TOPIC_CREATED")) {
                    System.out.println("主题 '" + topicName + "' 创建成功");
                } else if (response != null && response.equals("TOPIC_EXISTS")) {
                    System.out.println("主题 '" + topicName + "' 已存在");
                } else {
                    System.out.println("创建主题失败: " + (response != null ? response : "无响应"));
                }
            }
        } catch (Exception e) {
            // 如果连接失败，检查本地实例
            if (server != null && server.isRunning()) {
                MessageQueue messageQueue = server.getMessageQueue();
                if (messageQueue == null) {
                    System.out.println("无法获取消息队列实例");
                    return;
                }

                boolean created = messageQueue.createTopic(topicName);
                if (created) {
                    System.out.println("主题 '" + topicName + "' 创建成功");
                } else {
                    System.out.println("主题 '" + topicName + "' 已存在");
                }
            } else {
                System.out.println("服务器未启动或无法连接: " + e.getMessage());
            }
        }
    }

    /**
     * 删除主题
     */
    private static void deleteTopic(String topicName) {
        // 默认端口和主机
        int port = 7777;
        String host = "localhost";
        
        try {
            // 尝试连接服务器删除主题
            Socket socket = new Socket(host, port);
            try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ) {
                // 发送删除主题命令
                out.println("DELETE_TOPIC " + topicName);
                
                // 读取服务器响应
                String response = in.readLine();
                if (response != null && response.equals("TOPIC_DELETED")) {
                    System.out.println("主题 '" + topicName + "' 删除成功");
                } else if (response != null && response.equals("TOPIC_NOT_FOUND")) {
                    System.out.println("主题 '" + topicName + "' 不存在");
                } else {
                    System.out.println("删除主题失败: " + (response != null ? response : "无响应"));
                }
            }
        } catch (Exception e) {
            // 如果连接失败，检查本地实例
            if (server != null && server.isRunning()) {
                MessageQueue messageQueue = server.getMessageQueue();
                if (messageQueue == null) {
                    System.out.println("无法获取消息队列实例");
                    return;
                }

                boolean deleted = messageQueue.deleteTopic(topicName);
                if (deleted) {
                    System.out.println("主题 '" + topicName + "' 删除成功");
                } else {
                    System.out.println("主题 '" + topicName + "' 不存在");
                }
            } else {
                System.out.println("服务器未启动或无法连接: " + e.getMessage());
            }
        }
    }

    /**
     * 打印帮助信息
     */
    private static void printHelp() {
        System.out.println("SeeDog消息队列管理工具");
        System.out.println("可用命令:");
        System.out.println("  start [--port <port>] [--distributed]  - 启动消息队列服务器");
        System.out.println("  status                                - 检查服务器状态");
        System.out.println("  topics                                - 列出所有已创建的主题");
        System.out.println("  create-topic <topic-name>             - 创建新主题");
        System.out.println("  delete-topic <topic-name>             - 删除主题");
        System.out.println("  help                                  - 显示帮助信息");
    }
}